<template>
  <div class="navbar">
    <!--<span class="iconbtn">-->
    <!--<img src="../../../../static/img/mainLogo.png">-->
    <!--CBI-->
    <!--&lt;!&ndash;<i class="el-icon-d-arrow-left" :class="{rotate: !sidebar.opened}" @click="toggleSideBar"></i>&ndash;&gt;-->
    <!--</span>-->
    <!--<hamburger class="hamburger-container" :toggleClick="toggleSideBar" :isActive="sidebar.opened"></hamburger>-->

    <!--<breadcrumb class="breadcrumb-container"></breadcrumb>-->
    <img src="../../../../static/img/navlogo.png" alt="" style="width: 70px;position:relative;bottom:-6px;" :class="{inside: !sidebar.opened, outside: sidebar.opened}">
    <div class="right-menu">
      <!--<error-log v-if="log.length>0" class="errLog-container right-menu-item" :logsList="log"></error-log>-->
      <span class="feedback" @click="feedback">
        <!-- <img style="vertical-align: middle;" src="../../../../static/img/hand.png" height="20" width="20"> -->
        <i class="iconfont icon-wentifankui" style="font-size:26px;cursor: pointer;color:#000;"></i>
      </span>
      <div class="feedbackBox" v-if="showFeedback">
        <Header
          :teamName="$t('feedback.title')"
          :imageUrl="agentProfile.imageUrl"
          :onClose="closeFeedback"></Header>
        <div class="content">
          <div class="dialog" v-show="submitTip">
            <div class="tip">
              <img class="img" style="vertical-align:middle;margin-left:16px;margin-right:14px;" src="./image/ok.png" height="22" width="22"><span>{{$t('select.tip')}}</span>
            </div>
          </div>
          <div style="color:#666">{{$t('feedback.type')}}</div>
          <select class="select" name="" id="" v-model="feedbackData">
            <option value="Suggestion">{{$t('feedback.Suggestion')}}</option>
            <option value="Bug">Bug</option>
            <option value="DataError">{{$t('feedback.DataError')}}</option>
          </select>
          <div class="description">
            <textarea
              type="text"
              class="textarea"
              v-model="feedbackContent"
              @focus="textAreaInfo = false"
              :placeholder="$t('feedback.description')"></textarea>
            <span>{{contentLen}}/{{contentMaxLen}}</span>
          </div>
          <div style="line-height: 25px">
            <span v-show="textAreaInfo" class="showInfo">{{$t('feedback.contentInfo')}}</span>
          </div>
          <div class="addPictures">
            <el-upload ref="upload"
                       class="upload-demo"
                       style="line-height: 20px"
                       action="https://mail.cbitest.lenovo.com/feedback"
                       :before-upload="handleUpload"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :on-progress="handleProgresse"
                       :on-change="loadJsonFromFile"
                       :auto-upload="false"
                       multiple
                       :limit="2"
            >
              <span>{{$t('feedback.addPictures')}}&nbsp;&nbsp;( {{fileList.length}}/{{pictureMaxLen}} )</span>
            </el-upload>
          </div>
          <div style="line-height: 25px">
            <span v-show="uploadInfo" class="showInfo">{{$t('feedback.pictureInfo')}}</span>
          </div>
          <div class="submit">
            <div class="btn rightd" @click="submitFeedback1(feedbackData)">{{$t('feedback.submit')}}</div>
            <!-- <div class="btn" @click="hideFeedback">{{$t('feedback.cancel')}}</div> -->
          </div>
        </div>
      </div>
      <div class="Faq">
        <!--<i class="iconfont icon-service"></i>-->
        <!--<router-link to="/faqInside"><i class="iconfont icon-wenda"></i></router-link>-->
        <div>
          <beautiful-chat
            :agentProfile="agentProfile"
            :onMessageWasSent="onMessageWasSent"
            :messageList="messageList"
            :newMessagesCount="newMessagesCount"
            :isOpen="isChatOpen"
            :close="closeChat"
            :open="openChat"
            :showEmoji="true"
            :showFile="false">
          </beautiful-chat>
        </div>
      </div>
      <el-dropdown placement="bottom" class="avatar-container" trigger="click">
        <div class="avatar-wrapper">
          <!--<img class="user-avatar" :src="avatar+'?imageView2/1/w/80/h/80'">-->
          <!--  <i class="iconfont icon-gerentouxiang-" style="margin-top: 0"></i> -->
          <img src="../../../../static/img/myuser.png" style="vertical-align: middle;" alt="">
        </div>
        <el-dropdown-menu class="user-dropdown" slot="dropdown">
          <el-dropdown-item style="cursor: default">
            <!--{{name}}-->
            {{singleName}}
          </el-dropdown-item>
          <el-dropdown-item divided><span @click="logout" style="display:block;">{{$t("message.LogOut")}}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div class="lang">
        <span class="english" :class="{isLangActive: language === 'en'}" @click="changeEn">EN</span> / <span
        class="chinese"
        :class="{isLangActive: language === 'zh'}"
        @click="changeCh">中文</span>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import Breadcrumb from '@/components/Breadcrumb'
  import Hamburger from '@/components/Hamburger'
  import ThemePicker from '@/components/ThemePicker'
  import Screenfull from '@/components/Screenfull'
  import ErrorLog from '@/components/ErrLog'
  import errLogStore from 'store/errLog'
  import {getUsername, getToken} from '../../../utils/auth.js'
  import Header from '../../chatRobot/Header.vue'

  export default {
    components: {
      Breadcrumb,
      Hamburger,
      ThemePicker,
      ErrorLog,
      Screenfull,
      Header
    },
    data() {
      return {
        singleName: '',
        file: '',
        textAreaInfo:false,
        uploadInfo:false,
        pictureMaxLen: 2,
        fileList: [
          // {
          //   name: 'food.jpeg',
          //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          // }, {
          //   name: 'food2.jpeg',
          //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          // }
        ],
        submitTip: false,
        imageUrl: '',
        feedbackData: 'Suggestion',
        showFeedback: false,
        feedbackContent: '',
        feedbackAcceptor: {
          Suggestion: 'dongjy2@lenovo.com, zhangliang22@lenovo.com, wangpp10@lenovo.com',
          Bug: 'zhuyue3@lenovo.com, quyl1@lenovo.com, shiwf2@lenovo.com, fanxf4@lenovo.com, wangzq13@lenovo.com, wangxh30@lenovo.com, wangpp10@lenovo.com, jiangzl5@lenovo.com',
          DataError: 'changjy1@lenovo.com, wangsl8@lenovo.com, yubz1@lenovo.com, pengxj5@lenovo.com, wangzy32@lenovo.com, ligang15@lenovo.com, zhaoxr7@lenovo.com, shafei1@lenovo.com, luxw2@lenovo.com, dongxuan2@lenovo.com,baili2@lenovo.com,zhangge2@lenovo.com'
        },
        feedbackres: '',
        contentLen: '0',
        contentMaxLen: '200',
        log: errLogStore.state.errLog,
        lang: 'en',
        // 机器人
        agentProfile: {
          teamName: 'CBI-The Best Team',
          // imageUrl: 'https://a.slack-edge.com/66f9/img/avatars-teams/ava_0001-34.png'
          imageUrl: '../../static/img/chat-logo2.png'
        },
        messageList: [], // 界面展示的数组消息列表
        newMessagesCount: 0,
        isChatOpen: false,
        // 服务器这边的消息格式
        serviceTxt: {
          author: 'them',
          type: 'text',
          data: {
            text: 'some text'
          }
        },
        // 客户端这边的消息格式
        clientData: {
          author: 'me',
          type: 'text',
          data: {
            text: '消息'
          }
        },
        clientTxt: {
          author: 'me',
          type: 'emoji',
          data: {
            code: 'someCode'
          }
        },
        formData:new FormData()
      }
    },
    computed: {
      ...mapGetters([
        'sidebar',
        'name',
        'avatar',
        'language'
      ])
    },
    watch: {
      '$route' () {
        this.showFeedback = false
      },
      feedbackContent (value) {
        this.contentLen = value.length;
        if (value.length >= Number(this.contentMaxLen)) {
          this.feedbackContent = this.feedbackContent.substring(0, Number(this.contentMaxLen))
        }
        if(value.length === 0){
          this.textAreaInfo = true
        }else{
          this.textAreaInfo = false
        }
      },
      messageList (value) {
      },
      showFeedback (value) {
        if (value === false) {
          this.submitTip = false
        }
      }
    },
    methods: {
      loadJsonFromFile(file,fileList){
        this.uploadInfo=false;
        this.fileList.push(file.raw);
        if(this.fileList.length>1&&this.fileList[0].name===this.fileList[1].name){
          this.fileList.pop();
          fileList.pop();
          this.uploadInfo=true;
          return;
        }
      },
      handleUpload(file) {
        // console.log(file,'before')
        // this.file = file
      },
      handleProgresse(file, fileList) {
        // this.fileList = fileList
      },
      handleRemove(file, fileList) {
        this.fileList= this.fileList.filter(item=>item.name!==file.name)
        // console.log(11,this.fileList)
        if(this.fileList.length === 0){
          this.uploadInfo = false
        }
      },
      handlePreview(file) {
//         console.log(file,111);
      },
      // 以上是upload
      closeFeedback () {
        this.showFeedback = false;
        this.fileList.length=0;
      },
      submitFeedback1 (data) {
        let to = '';
        if(this.feedbackContent === ''){
          this.textAreaInfo = true;
          return
        }
        if (data === 'Suggestion') {
          to = this.feedbackAcceptor.Suggestion
        }
        if (data === 'Bug') {
          to = this.feedbackAcceptor.Bug
        }
        if (data === 'DataError') {
          to = this.feedbackAcceptor.DataError
        }
        this.formData.append('to', to)
        this.formData.append('cc', '')
        this.formData.append('subject', 'FeedBack')
        this.formData.append('category', data)
        this.formData.append('content', this.feedbackContent)
        for (let i=0;i<this.fileList.length;i++){
          this.formData.append('file', this.fileList[i]);
        }
        this.axios.post('https://mail.cbitest.lenovo.com/feedback', this.formData).then(res => {
          if (res.data.msg === 'success') {
            this.feedbackres = res.data.data
            this.submitTip = true
            setTimeout(()=>{
              this.submitTip = true
              this.uploadInfo = false
            },1500)
          } else {
            this.feedbackres = res.data.data
            this.openVn()
            this.showFeedback = false
          }
        })
      },
      openVn() {
        const h = this.$createElement;
        this.$message({
          message: h('p', null, [
            h('span', null, this.feedbackres)
          ])
        });
      },
      hideFeedback () {
        this.showFeedback = false
      },
      feedback () {
        this.closeChat()
        this.feedbackContent = ''
        this.uploadInfo = false
        this.textAreaInfo = false
        this.fileList.length = 0
        if (this.showFeedback === false) {
          this.showFeedback = true
        } else {
          this.showFeedback = false
        }
      },
      toggleSideBar() {
        this.$store.dispatch('toggleSideBar')
      },
      // 切换中英文
      changeCh() {
        this.lang = "zh";
        this.$i18n.locale = this.lang;
        this.$store.dispatch('setLanguage', this.lang)
      },
      changeEn() {
        this.lang = "en";
        this.$i18n.locale = this.lang;
        this.$store.dispatch('setLanguage', this.lang)
      },
//    handleSetLanguage(lang) {
//      console.log(lang)
//      this.$i18n.locale = lang
//      this.$store.dispatch('setLanguage', lang)
////      this.$message({
////        message: 'switch language success',
////        type: 'success'
////      })
//    },
      logout() {
        this.$store.dispatch('LogOut').then(() => {
          Avatar.push([
            "track",
            [
              "category",
              "Logout",
              "label",
              {
                userName: getUsername()
              },
              0
            ]
          ]);
          location.reload()// 为了重新实例化vue-router对象 避免bug
          // this.$router.push({path: '/login'})
        })
      },
      // 服务器发送给客户端
      sendMessage(msg) {
        // if (text.length > 0) {
        this.newMessagesCount = this.isChatOpen ? this.newMessagesCount : this.newMessagesCount + 1
        this.messageList.push(msg)
        // }
      },
      // 展示在客户端的数组消息列表
      onMessageWasSent(msg) {
        const _this = this
        if (msg.type === 'text') {
          var paramsData = msg.data.text
        } else if (msg.type === 'emoji') {
          var paramsData = msg.data.emoji
        }
        // console.log(paramsData)
        // var firstLetter = paramsData.substr(0, 1)
        function typeFlag (data) {
          if (data.flag === 1) {
            return loopArray(data.detail, '1')
          } else if (data.flag === 2) {
            return loopArray(data.detail, '2')
          } else if (data.flag === 3) {
            return loopArray(data.detail, '3')
          }
        }
        function loopArray (data, type) {
          let answerArrs = []
          let answerArr = {a: ''}
          if (type === '1' || type === '2') {
            for (let i in data) {
              answerArr.a = data[i]['answer-info']
              answerArrs.push(answerArr.a)
            }
          } else if (type === '3') {
            for (let i in data) {
              answerArr.a = ''
              for (let j in data[i]) {
                if (j === 'answer-info') {
                  answerArr.a += `Event Title:<a href=${data[i].url} style="text-decoration:underline;color:#4e8cff;" target="_blank">${data[i][j]}</a>\n`
                } else if (j === 'answer-type') {
                  answerArr.a += `Event Type:${data[i][j]}\n`
                } else if (j === 'url') {} else if (j === 'date') {
                  answerArr.a += `Event Date:${data[i][j]}\n`
                }
              }
              answerArrs.push(answerArr.a)
            }
          }
          return answerArrs
        }
        this.messageList.push(msg)
        this.axios.post('https://ask.cbitest.lenovo.com/robot/ask', {
          question: paramsData
        }).then( res => {
          // console.log('返回的数据')
          // console.log(res)
          var resData = res.data
          // console.log(resData)
          // 返回的消息
          var sendAnswer = resData.data.answer
          var sendTime = resData.time
          // console.log('返回的消息')
          // console.log(sendAnswer)
          // var sendAnswer1 = ''
          // if (sendAnswer.indexOf('{') === -1) {
          //   sendAnswer1 = sendAnswer
          // } else {
          //   let sends = eval(sendAnswer)
          //   for (let i in sends[0]) {
          //     if (i === 'answer') {
          //       sendAnswer1 += `Event ${this.ucfirst(`title`)}:<a href=${sends[0].url} style="text-decoration:underline;color:#4e8cff;" target="_blank">${sends[0][i]}</a>\n`
          //     } else if (i === 'answer-type') {
          //       sendAnswer1 += `Event ${this.ucfirst(`type`)}:${sends[0][i]}\n`
          //     } else if (i === 'url') {} else {
          //       sendAnswer1 += `Event ${this.ucfirst(i)}:${sends[0][i]}\n`
          //     }
          //   }
          // }
          // console.log(typeFlag(typeChange(sendAnswer)), '*******')
          let allSay = typeFlag(sendAnswer)
          // for (let i = 0; i < allSay.length; i++) {
          //   var sendAnswerObject = {
          //     author: 'them',
          //     type: 'text',
          //     data: {
          //       text: allSay[i]
          //     }
          //   }
          //   // sendAnswerObject.data.text = allSay[i]
          //   console.log(allSay[i], 'sendAnswerObject')
          //   this.sendMessage(sendAnswerObject)
          // }
          allSay.forEach(value => {
            var sendAnswerObject = {
              author: 'them',
              type: 'text',
              data: {
                text: value
              }
            }
            this.sendMessage(sendAnswerObject)
          })
          // if (paramsData === undefined || paramsData.charCodeAt(0) > 255) {
          //   // console.log('首字母是中文')
          //   var sendAnswerObject = {
          //     author: 'them',
          //     type: 'text',
          //     data: {
          //       text: sendAnswer.zh
          //     }
          //   }
          // } else {
          //   // console.log('首字母不是中文')
          //   var sendAnswerObject = {
          //     author: 'them',
          //     type: 'text',
          //     data: {
          //       text: sendAnswer.en
          //     }
          //   }
          // }
          /*_this.sendMessage(sendAnswerObject)*/
        })
      },
      openChat() {
        this.isChatOpen = true
        this.newMessagesCount = 0
        this.showFeedback = false
      },
      closeChat() {
        this.isChatOpen = false
      }
    },
    created() {
      let nameStr = getToken()
      this.singleName = nameStr.slice(0, nameStr.indexOf('_'))
      console.log(this.singleName, 999)
    },
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .navbar {
    .iconfont:hover{
      color:#409EFF;
    }
    background-color: #fff;
    height: 50px;
    position: fixed;
    top: 0;
    width: 100%;
    /*z-index: 9999;*/
    z-index: 1000;
    line-height: 50px;
    box-shadow: 0 2px 10px 0 rgba(226, 224, 234, .6);
    border-radius: 0px !important;
    .inside {
      margin-left: 85px;
      transition: transform 0.1s ease-in-out, left 0.1s ease-in-out, margin-left 0.1s ease-in-out;
    }
    .outside {
      margin-left: 248px;
      transition: transform 0.1s ease-in-out, left 0.1s ease-in-out, margin-left 0.1s ease-in-out;
    }
    .iconbtn {
      display: inline-block;
      outline: none;
      line-height: 50px;
      user-select: none;
      float: left;
      font-weight: 600;
      color: #5a5e66;
      font-size: 1.5rem;
      img {
        width: 35px;
        display: inline-block;
        vertical-align: top;
        margin-top: 5px;
        margin-left: 10px;
      }
      .el-icon-d-arrow-left {
        margin-left: 20px;
        cursor: pointer;
      }
      .rotate {
        transform: rotate(180deg);
      }
    }
    .hamburger-container {
      line-height: 58px;
      height: 50px;
      float: left;
      padding: 0 10px;
      margin-left: 20px;
    }
    .breadcrumb-container {
      float: left;
    }
    .errLog-container {
      display: inline-block;
      vertical-align: top;
    }
    .right-menu {
      float: right;
      height: 100%;
      &:focus {
        outline: none;
      }
      .lang {
        float: right;
        margin-right: 20px;
        .english, .chinese {
          cursor: pointer;
          color: #5a5e66;
          font-weight: bold;
        }
        .isLangActive {
          color: #409EFF;
        }
      }
      .feedback {
        display: inline-block;
        margin-right: 10px;
        cursor:pointer;
      }
      .feedbackBox {
        /*width: 400px;*/
        /*height: 440px;*/
        border-radius: 9px;
        width: 367px;
        border:2px solid #f2f2f2;
        position: absolute;
        right: 46px;
        top: 50px;
        z-index: 999;
        background: #fff;
        .sc-header{
          width:365px;
          background: #969696;
        }
        .dialog{
          width: 100%;
          height: 106%;
          background: rgba(0, 0, 0, 0.4);
          position: absolute;
          top:0;
          left:0;
          border-radius:5px;
          z-index:999;
          padding: 0 16px;
          .tip{
            margin-top:127px;
            width: 100%;
            background: #fff;
          }
        }
        .header{
          height: 50px;
          line-height: 50px;
          text-align: center;
          background: #d7d7d7;
        }
        .description {
          position: relative;
          height: 123px;
          /*margin-top: -20px;*/
          .textarea {
            position: relative;
            margin-top: -5px;
            /*width:100%;*/
            /*height: 124px;*/
            width:326px;
            height: inherit;
            background:#ecf3f9;
            border-radius: 4px;
            border:1px solid rgba(153,153,153,.3);
            resize:none;
            padding-left: 10px;
            line-height:24px;
            font-size:14px;
          }
          span{
            float:right;
            color:#0090e9;
            font-size:10px;
            position:absolute;
            bottom:-5px;
            right:15px;
          }
          .textarea::-webkit-input-placeholder{
            padding:5px 0 0 6px;
            color:#ccc;
            font-size:14px;
          }

          .textarea::-moz-placeholder{   /* Mozilla Firefox 19+ */
            padding:5px 0 0 6px;
            color:#ccc;
            font-size:14px;
          }
          .textarea:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
            padding:5px 0 0 6px;
            color:#ccc;
            font-size:14px;
          }
          .textarea:-ms-input-placeholder{  /* Internet Explorer 10-11 */
            padding:5px 0 0 6px;
            color:#ccc;
            font-size:14px;
          }
        }
        .showInfo{
          color:#f00;
        }
        .addPictures{
          margin-top:-5px;
          color:#9fc6ee;
          font-size:14px;
          label{
            cursor: pointer;
          }
          .el-upload{
            line-height:30px;
            .el-upload-list__item:first-child{
              margin-top:0 !important;
            }
          }
        }
        .submit {
          margin: 20px 0;
          .btn{
            /*width: 130px;*/
            width: 100%;
            height: 40px;
            line-height: 40px;
            /*float:right;*/
            /*background: #a3abf6;*/
            background: #ffac00;
            text-align: center;
            cursor: pointer;
            border-radius: 5px;
            color: #fff;
            &:hover{
              background: #ff5b00;
            }
          }
          .rightd{
            margin-right: 0px;
          }
        }
        .content{
          position: relative;
          padding: 0 16px;
          width: 365px;
          margin-bottom: -2px;
          .select{
            /*width: 100%;*/
            padding-left: 10px;
            width:326px;
            height: 30px;
            position: relative;
            top: -15px;
            /*color:#111;*/
            background:#ecf3f9;
            color:#666;
            font-size:14px;
            border-radius: 4px;
            border:1px solid rgba(153,153,153,.3);
          }
        }
      }
      .Faq {
        display: inline-block;
        margin-right: 20px;
        /*cursor: pointer;*/
        color: #5a5e66;
        i {
          font-size: 20px;
          color: #000;
        }
        &:hover {
          color: #409EFF;
        }
      }
      .right-menu-item {
        display: inline-block;
        margin: 0 8px;
      }
      .screenfull {
        height: 20px;
      }
      .international {
        margin-right: 20px;
        vertical-align: top;
        .international-icon {
          font-size: 20px;
          cursor: pointer;
          vertical-align: -5px;
        }
      }
      .theme-switch {
        vertical-align: 15px;
      }
      .avatar-container {
        float: right;
        height: 50px;
        margin-right: 30px;
        .avatar-wrapper {
          cursor: pointer;
          position: relative;
          i {
            font-size: 18px;
            font-weight: 600;
          }
          .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
          }
          .el-icon-caret-bottom {
            position: absolute;
            right: -20px;
            top: 25px;
            font-size: 12px;
          }
        }
      }
    }
  }
</style>



